﻿
using Common;
using NB.MGJ.Model;
using NB.MGJ.Service;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NB.MGJ.WebWap.Controllers.Marketing;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common;
using WebAppModel;
using NB.MGJ.Service.Market;

namespace NB.MGJ.WebWap.Controllers.Marketing
{
    public class MarketingController : Controller
    {
        ManagerService _manger = new ManagerService();
        MarketService _MarketService = new MarketService();
        TheWinningService _the = new TheWinningService();
        DBHService _dbhService = new DBHService();

        /// <summary>
        /// 获取活动加载图片IOS
        /// </summary>
        /// <returns></returns>
        public string GetLaodImgUrl() 
        {
            UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
         string  PagelaodImgUrl=  _MarketService.GetActivityInfo(_MarketService.GetActivityModel(user.Aid).ActivityInfoID.Value).PagelaodImgUrl;
         return PagelaodImgUrl;
        }

        /// <summary>
        /// 判断是否有活动 有就返回活动
        /// </summary>
        /// <param name="codeStr">解密的code</param>
        /// <returns></returns>
        public ActionResult IsMarketing( string address)
        {
            try
            {
                UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
                user.address = address;
                string codeStr=user.JiemiCode;
                int eid = user.Eid;
                Marketing_Activity activity = _MarketService.GetActivity_Issue(eid, user.BatchId);
                Hashtable ht = new Hashtable();
                WeiXinHelper.WriteLog("address", address);
                ht.Add("count", _the.GetThewinningCount(activity.Id, user.eCode));
                    //活动区域限制
                    if (activity.IsLimitArea == 1 && !string.IsNullOrEmpty(address))
                    {
                        var adds = address.Split(',');
                        var province = adds.Length > 0 ? adds[0] : "";
                        var city = adds.Length > 1 ? adds[1] : "";
                        if (activity.City.IndexOf(city) == -1 && activity.Privance.IndexOf(province) == -1)
                        {  //当前网络地址不在活动范围
                            ht.Add("b", "0");//没有活动
                            return Json(ht, JsonRequestBehavior.AllowGet);
                        }
                    }

                    ht.Add("address", address);
                    Marketing_Template tem = _MarketService.GetTemplateModel((int)activity.TemplateID);
                    ht.Add("html", tem.ActivityHome.Replace(" ", "+"));
             
                    ht.Add("tid", tem.ID);

                    // 活动ID  和 模板ID 存入Session["user"] 
                    user.Aid = Convert.ToInt32(activity.Id);
                    user.TId = Convert.ToInt32(activity.TemplateID);
                    Session["user"] = user;
                    ht.Add("Activity", activity);

                    string tableCode = eid.ToString().PadLeft(4, '0');
               
                        //判断次数
                        Marketing_Delivery delivery = _MarketService.GetDeliveryById(Convert.ToInt32(activity.DeliveryId));

                        PagerModel pm = new PagerModel();
                        int ChanceNum = 0;
                        #region     限制  每人总抽奖机会次数    每天中奖次数  每人中奖次数
                        //限制每人总抽奖机会次数
                        string where = " t.ActivityID=" + activity.Id + " and u.id=" + user.Uid;
                        pm.StrCondition = where;
                        pm.Page = 1;
                        pm.PageSize = 1000;  //每人最多抽奖1000次
                        if (_MarketService.GetTheWinningList(ref pm, tableCode).TotalItemCount >Convert.ToInt32(delivery.EachGetSumNum))
                        {
                            ht.Add("b", "-1");   // 已经超出 每人总抽奖机会次数
                            ht.Add("ChanceNum", ChanceNum);
                            return Json(ht, JsonRequestBehavior.AllowGet);
                        }

                        //获取扫码用户的活动  每人中奖次数
                        pm.StrCondition = " t.ActivityID=" + activity.Id + " and u.id=" + user.Uid + " and t.AwardsID>0";
                       
                        if (_MarketService.GetTheWinningList(ref pm, tableCode).TotalItemCount > Convert.ToInt32(delivery.EachGetPrizeNum))
                        {
                            ht.Add("ChanceNum", ChanceNum);
                            ht.Add("b", "-2");//  已经超出 每人中奖次数
                            return Json(ht, JsonRequestBehavior.AllowGet);
                        }

                        string dt = DateTime.Now.ToString("yyyy-MM-dd");

                        //获取扫码用户的活动  每日抽奖次数  
                        pm.StrCondition = "   t.ActivityID=" + activity.Id + " and u.id=" + user.Uid + " and Time like '" + dt + "%'";

                        if (_MarketService.GetTheWinningList(ref pm, tableCode).TotalItemCount > Convert.ToInt32(delivery.DayGetPrizeNum))
                        {
                            ht.Add("b", "-3");//有活动  已经超出  每日中奖次数 
                            ht.Add("ChanceNum", ChanceNum);
                            return Json(ht, JsonRequestBehavior.AllowGet);
                        }
                        #endregion
                        ChanceNum = Convert.ToInt32(delivery.DayGetPrizeNum) - _MarketService.GetTheWinningList(ref pm, tableCode).TotalItemCount;
                        ht.Add("ChanceNum", ChanceNum);
                return Json(ht, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("判断活动err", ex.ToString());
                throw;
            }

        }



        /// <summary>
        /// 判断活动状态  
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMarketingState() 
        {
            try
            {
            Hashtable ht = new Hashtable();
            UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
            int eid = user.Eid;
           
            string tableName = "marketing.Marketing_TheWinning" + user.eCode;
            string uTableName = "marketing.marketing_user" + user.eCode;
            WeiXinHelper.WriteLog("tableName", tableName);
            Marketing_TheWinning thewinning = _MarketService.IsTheWinningData(tableName, user.JiemiCode, uTableName);
            if (thewinning.State==null  && (Session["user"] as UserScanQRInfoModel).Uid == thewinning.UserID)
            {
                ht.Add("b", "1");//是同一个人扫码       通过
                ht.Add("Awards", _MarketService.GetAwardsModel(Convert.ToInt32(thewinning.AwardsID)));

            }
            else if (thewinning.State ==EnumManagement.GetEnumValue( EnumTheWinningState.GetAwardSucceed)) //领取成功！
            {
                ht.Add("b", "2");//该码已经被领奖
                ht.Add("record", thewinning);
                user.AwId = Convert.ToInt32(thewinning.AwardsID);
                user.Denomination = thewinning.Denomination;
            }
            else if (thewinning.State ==EnumManagement.GetEnumValue( EnumTheWinningState.NotGetDraw) && (Session["user"] as UserScanQRInfoModel).Uid == thewinning.UserID)
            {
                ht.Add("record", thewinning);
                ht.Add("Awards", _MarketService.GetAwardsModel(Convert.ToInt32(thewinning.AwardsID)));
                ht.Add("b", "3");//有活动 活动被扫码过  但用户没有领取   确定是本人在次扫码
                user.AwId = Convert.ToInt32(thewinning.AwardsID);
                user.Denomination = thewinning.Denomination;
            }
            else
            {
                ht.Add("b", "2");//有活动 但码已经被扫码  或被领取  
                ht.Add("record", thewinning);
                user.AwId = Convert.ToInt32(thewinning.AwardsID);
                user.Denomination = thewinning.Denomination;
            }
            return Json(ht, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("state",ex.ToString());
                throw;
            }
        }
    }
}